<?php

class CMealsEvent {
	
	/**
	 * Create event group record and events/crew assignments in database - CMWK method.
	 * @param $year YYYY
	 * @param $week WW
	 * @param $eventDayList array of days in the week {"MO", "TU", "WE", "TH", "FR", "SA", "SU"} (events will be created)
	 * @param $eventType CMeals::TYPE_*
	 * @param $crewNameList array of crew names
	 */
	public static function createEventGroupCMWK($year, $week, $eventDayList, $crewNameList) {
		// Prepare event group
		$eventGroup = new cmeals_std_class();
		$eventGroup->id = "CMWK".$year.$week;
		$eventGroup->description = $year."/".$week;
		// Check that event group does not already exist
		if (NULL != CMeals::readEventGroup($eventGroup->id)) {
			CMeals::getErrorHandler()->handleError("DUPLICATE_ENTRY_ERROR", $year."/".$week);
			return false;
		}
		// Prepare events
		$eventList = array();
		// Keys must match CMeals::readEventSubTypeList(CMeals::TYPE_COMMUNAL_MEAL)
		$dayNumber = array("MO"=>"1", "TU"=>"2", "WE"=>"3", "TH"=>"4", "FR"=>"5", "SA"=>"6", "SU"=>"7");
		$valideventDays = array();
		foreach (CMeals::readEventSubTypeList(CMeals::TYPE_COMMUNAL_MEAL) as $eventSubType) {
			$valideventDays[$eventSubType->id] = $eventSubType->display_name;
		}
		foreach ($eventDayList as $eventDay) {
			if (array_key_exists($eventDay, $valideventDays)) {
				$event = new cmeals_std_class();
				$event->id = $eventDay;
				$event->group_id = $eventGroup->id;
				$event->type = CMeals::TYPE_COMMUNAL_MEAL;
				$event->subtype = $eventDay;
				$event->status = CMeals::STATUS_PLANNING;
				$event->date = date("Y-m-d", strtotime($year.'W'.$week.$dayNumber[$eventDay]));
				$eventList[] = $event;
			}
			else {
				CMeals::getErrorHandler()->handleError("INVALID_EVENT_DAY_ERROR", $eventDay);
				return false;
			}
		}
		// Prepare crew assignments
		$crewList = array();
		$memberList = CMeals::readMemberList();
		foreach ($crewNameList as $crewName) {
			$memberId = null;
			foreach ($memberList as $member) {
				if ($member->name == $crewName) {
					$memberId = $member->id;
				}
			}
			if (!is_null($memberId)) {
				$crew = new cmeals_std_class();
				$crew->member_id = $memberId;
				$crew->group_id = $eventGroup->id;
				$crewList[] = $crew;
			}
			else {
				CMeals::getErrorHandler()->handleError("INVALID_MEMBER_NAME", $crewName);
				return false;
			}
		}
		// Write to database
		CMeals::createEventGroup($eventGroup);
		foreach ($eventList as $event) {
			CMeals::createEvent($event);
		}
		foreach ($crewList as $crew) {
			CMeals::createCrew($crew);
		}
	}
		
	/**
	 * Save an already existing event
	 * @param $event event object
	 */
	public static function saveEvent($event) {
		if (CMeals::isEventCrew(CMealsFrontEndUtils::getCurrentMemberId(), $event->group_id, $event->id)) {
			CMeals::updateEventDelta($event);
		}
		else {
			$err = CMeals::getErrorHandler();
			$err->handleError("NOT_AUTHORISED", "");
		}
	}
	
	/**
	 * Save an already existing event group
	 * @param $eventGroup
	 */
	public static function saveEventGroup($eventGroup) {
		if (CMeals::isEventGroupCrew(CMealsFrontEndUtils::getCurrentMemberId(), $eventGroup->id)) {
			CMeals::updateEventGroupDelta($eventGroup);
		}
		else {
			$err = CMeals::getErrorHandler();
			$err->handleError("NOT_AUTHORISED", "");
		}
	}

	/**
	 * Set status for one event or all events in group
	 * @param $status one of CMeals::STATUS_*
	 * @param $group_id event group id
	 * @param $event_id event id (optional, if omitted all events in group are affected)
	 */
	public static function updateEventStatus($status, $group_id, $event_id=null) {
		if (is_null($event_id)) {
			if (CMeals::isEventGroupCrew(CMealsFrontEndUtils::getCurrentMemberId(), $group_id)) {
				CMeals::updateEventStatus($status, $group_id);			
			}
			else {
				$err = CMeals::getErrorHandler();
				$err->handleError("NOT_AUTHORISED", "");
			}
		}
		else {
			if (CMeals::isEventCrew(CMealsFrontEndUtils::getCurrentMemberId(), $group_id, $event_id)) {
				CMeals::updateEventStatus($status, $group_id, $event_id);			
			}
			else {
				$err = CMeals::getErrorHandler();
				$err->handleError("NOT_AUTHORISED", "");
			}
		}
	}
		
	/** Enrich event group object with summarized status info for all its events
	 * Append:
	 *   $eventGroup->allEventsClosed boolean
	 *   $eventGroup->allEventsBilling boolean  
	 * 
	 * @param $eventGroup event group object
	 */ 
	public static function appendSummarizedEventStatus($eventGroup) {
		$allEventsClosed = true; // just an initial assumption
		$allEventsBilling = true; // just an initial assumption
		$allEventsArchive = true; // just an initial assumption
		$eventList = CMeals::readEventList($eventGroup->id);
		foreach ($eventList as $event) {
			if ($event->status < CMeals::STATUS_CLOSED) {
				$allEventsClosed = false; // If just one is not closed, then false
			}
			if ($event->status < CMeals::STATUS_BILLING) {
				$allEventsBilling = false; // If just one is not billing, then false
			}
			if ($event->status < CMeals::STATUS_ARCHIVE) {
				$allEventsArchive = false; // If just one is not archive, then false
			}
		}
		// Finally set the conclusion on all events closed/billing or not
		$eventGroup->allEventsClosed = $allEventsClosed;
		$eventGroup->allEventsBilling = $allEventsBilling;
		$eventGroup->allEventsArchive = $allEventsArchive;
	}
	
}

class CMealsSignup {
	
	/**
	 * Save sign-up
	 * @param $signUp signup object
	 */
	public static function saveSignUp($signUp) {
		if (count(CMeals::readSignUpList($signUp->group_id, $signUp->event_id, $signUp->member_id, $signUp->category)) == 0) {
			CMeals::createSignUp($signUp);
		}
		else {
			CMeals::updateSignup($signUp);
		}
	}

	/**
	 * Save automatic signup
	 * @param $autoSignUp auto signup object
	 */
	public static function saveAutoSignUp($autoSignUp) {
		if (count(CMeals::readAutoSignUpList($autoSignUp->member_id, $autoSignUp->event_type, $autoSignUp->event_subtype, $autoSignUp->category)) == 0) {
			CMeals::createAutoSignUp($autoSignUp);
		}
		else {
			CMeals::updateAutoSignup($autoSignUp);
		}
	}
	
	/** Enrich each event in a supplied list with sign-up data
	 * Append:
	 *   $event->categoryList        indexed array of valid sign-up categories for the event, by category
	 *   $event->categoryList->participantsSum     sum of participants for each category 
	 *   $event->categoryList->participantsList    indexed array of signed-up participants, by member_id
	 * 
	 * @param $eventList list of event objects
	 * @param $member member object (optional) if supplied, just data for that member, else for all members
	 */ 
	public static function appendSignupData($eventList, $member=NULL) {
		foreach ($eventList as $event) {
			if (is_null($member)) {
				$memberList = CMeals::readMemberList();
				if ($event->status <= CMeals::STATUS_PLANNING) {
					$signUpList = array();
					foreach ($memberList as $memberX) {
						$autoSignUpListPerMember = CMeals::readAutoSignUpList($memberX->id, $event->type, $event->subtype);
						foreach ($autoSignUpListPerMember as $autoSignUp) {
							$signUpList[] = $autoSignUp;
						}
					}
				}
				else {
					$signUpList = CMeals::readSignUpList($event->group_id, $event->id);
				}
			}
			else {
				$memberList = array($member);
				if ($event->status <= CMeals::STATUS_PLANNING) {
					$signUpList = CMeals::readAutoSignUpList($member->id, $event->type, $event->subtype);
				}
				else {
					$signUpList = CMeals::readSignUpList($event->group_id, $event->id, $member->id);
				}
			}
			$categoryList = CMeals::readEventCategoryList($event->type);
			$event->categoryList = array();
			// Make categoryList accessible by id
			foreach ($categoryList as $category) {
				$event->categoryList[$category->id] = $category;
			}
			self::appendParticipantsList($event, $signUpList, $memberList);
		}
	}
	
	private static function appendParticipantsList($event, $signUpList, $memberList) {
		foreach ($event->categoryList as $category) {
			$category->participantsList = array();
			foreach ($memberList as $member) {
				$category->participantsList[$member->id] = 0;
			}
		}
		foreach ($signUpList as $signUp) {
			$event->categoryList[$signUp->category]->participantsList[$signUp->member_id] = $signUp->participants; 
		}
		foreach ($event->categoryList as $category) {
			$category->participantsSum = 0;
			foreach ($memberList as $member) {
				$category->participantsSum += $category->participantsList[$member->id];
			}
		}
	}

}

?>